#!/bin/bash
# filename: duploadtiff
# description: upload tiff folder to DaRIS
# Toan Nguyen, June 2012
# V3: modified Nov 22, 2012

#     Copyright © 2012-2013 Toan Nguyen <toan.nguyen@monash.edu>
#
#     This file is part of Xglom.
# 
#     This is free software: you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
# 
#     This is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
# 
#     You should have received a copy of the GNU General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.



# ========= MAIN SCRIPT ============
# check system first
. dcheck

usage() {
    echo "Usage: duploadtiff [-h] [-r] -c cid -m ntilesver -n ntileshoz -x dx -y dy -z dz [-p original_dataset_cid] [-t step] [-o bzero] [-s bscale] [-b bunit] tiff_dir"
	# cid: DaRIS ID of subject or ex-method or study
	# step: step within the method that resulted in this study. Only need if cid is not a study cid.
}

# TIFF_NX TIFF_NY TIFF_NZ
# TIFF_DX (-x) TIFF_DY (-y) TIFF_DZ (-z)
# TIFF_BZERO TIFF_BSCALE TIFF_BUNIT
let REMOVE_ZIP_FILE=0

while getopts hm:n:x:y:z:o:s:b:c:rt:p: OPTION
do
     case $OPTION in
         h) usage
            exit 1
            ;;

         c) PARENT_CID=$OPTARG
            ;;
			
		 m) NTILE_X=$OPTARG
            ;;
		
		 n) NTILE_Y=$OPTARG
            ;;

         x) TIFF_DX=$OPTARG
            ;;

	     y) TIFF_DY=$OPTARG
            ;;

         z) TIFF_DZ=$OPTARG
            ;;

         o) TIFF_BZERO=$OPTARG
            ;;

         s) TIFF_BSCALE=$OPTARG
            ;;

         b) TIFF_BUNIT=$OPTARG
            ;;
         
         r) let REMOVE_ZIP_FILE=1
            ;;
		
		 t) STEP=$OPTARG
			;;
			
		 p) ORI_CID=$OPTARG
		    ;;

         ?) usage
            exit 1
            ;;
     esac
done
shift $(($OPTIND - 1))
TIFF_DIR=$1

if [ -z $PARENT_CID ] || [ -z $TIFF_DX ] || [ -z $TIFF_DY ] || [ -z $TIFF_DZ ] || [ -z $TIFF_DIR ] || [ -z $NTILE_X ] || [ -z $NTILE_Y ]; then
    echo "Error: not enough inputs"
    usage
    exit 1;
fi

# create study if provide cid of ex-method or subject
let need_create_study=0;
num_dots=`echo $PARENT_CID | grep -o '\.' | wc -l`

if [ $num_dots -eq 3 ]; then
    PARENT_CID="$PARENT_CID.1"
    let need_create_study=1;

elif [ $num_dots -eq 4 ]; then
    let need_create_study=1;
	
elif [ $num_dots -eq 5 ]; then
    STUDY_CID=$PARENT_CID

else
    echo "invalid cid"
	usage
	exit 1
fi

if [ -z $STEP ]; then
	let STEP=1
fi

if [ ! -d ${TIFF_DIR} ]; then
    echo "invalid directory!"
	exit 1;
fi

# create study if needed
if [ $need_create_study -eq 1 ]; then
    STUDY_CID=$( $MFCOMMAND om.pssd.study.create :pid ${PARENT_CID} :step ${STEP} | awk '{print $2}' | tr -d \" )
fi

#
 
if [ -f ./dpingloop ]; then
 ./dpingloop &
 pollingID=$!
fi


# convert relative path to absolute path"
TIFF_DIR=$( cd ${TIFF_DIR}; pwd )
#echo $TIFF_DIR

# Calculate TIFF_NX, TIFF_NY, TIFF_NZ
first_tiff_file=${TIFF_DIR}/$( ls ${TIFF_DIR} | head -1)

tmp=$(tiffdump ${first_tiff_file} | grep ImageLength )
tmp="${tmp#*<}"
TIFF_NX="${tmp%>*}"

tmp=$(tiffdump ${first_tiff_file} | grep ImageWidth)
tmp="${tmp#*<}"
TIFF_NY="${tmp%>*}"

TIFF_NZ=$(ls ${TIFF_DIR} | wc -l)

let TILE_HEIGHT=${TIFF_NX}/${NTILE_X}
let TILE_WIDTH=${TIFF_NY}/${NTILE_Y}

dataset_name="${TIFF_DIR##*/}_${TIFF_NX}_${TIFF_NY}_${NTILE_X}_${NTILE_Y}"

# create temp folder to upload inside tiff folder
#UPLOAD_DIR=/tmp/${dataset_name}
#UPLOAD_THUMB_DIR=/tmp/${dataset_name}_thumb
UPLOAD_DIR=${HOME}/Monash038_scratch/${dataset_name}
UPLOAD_THUMB_DIR=${HOME}/Monash038_scratch/${dataset_name}_thumb
echo create $UPLOAD_DIR $UPLOAD_THUMB_DIR

[ ! -d $UPLOAD_DIR ] && mkdir $UPLOAD_DIR
[ ! -d $UPLOAD_THUMB_DIR ] && mkdir $UPLOAD_THUMB_DIR

# create sub dirs and generate tiles
file_index=1

tiffiles=$(cd  ${TIFF_DIR}; /bin/ls -1 | sort -n )
# files=$( find ${TIFF_DIR} -type f -name "*.[tT][iI][Ff][fF]" )

for file in $tiffiles
do
    # create sub dirs
    sub_dir_name=${UPLOAD_DIR}/$( printf "%04d_%02d_%02d" ${file_index} ${NTILE_X} ${NTILE_Y} )
	# echo create ${sub_dir_name}	
    [ ! -d ${sub_dir_name} ] && mkdir -p ${sub_dir_name}
	
	# generate tiles
    let tile_index=1
    let tile_index_x=0
    while [ ${tile_index_x} -lt ${NTILE_X}  ]; do
		
	let tile_index_y=0
	while [ $tile_index_y -lt ${NTILE_Y} ]; do
		   
		   
	    tile_file_name=${sub_dir_name}/$(printf "%04d.tif" ${tile_index})
	    echo ${tile_file_name}
		   
		   # get tile and save to file
	    let offset_col=${tile_index_y}*${TILE_WIDTH}
	    let offset_row=${tile_index_x}*${TILE_HEIGHT}
	    if [ $NTILE_X -eq 1 ] && [ $NTILE_Y -eq 1 ]; then
		cp  ${TIFF_DIR}/${file} ${tile_file_name}
	    else
		convert -crop ${TILE_WIDTH}x${TILE_HEIGHT}+${offset_col}+${offset_row}  ${TIFF_DIR}/$file ${tile_file_name}
	    fi
	    let tile_index_y=tile_index_y+1
	    let tile_index=tile_index+1
	done
	let tile_index_x=tile_index_x+1
    done
	
	# save parameters to a text file
    # parameters="${file_index} ${TIFF_NX} ${TIFF_NY} ${NTILE_X} ${NTILE_Y} ${TIFF_NZ} ${TIFF_DX} ${TIFF_DY} ${TIFF_DZ} ${TIFF_BZERO} ${TIFF_BSCALE} ${TIFF_BUNIT}"
	# echo "file index, TIFF_NZ, TIFF_DX, TIFF_DY, TIFF_DZ, TIFF_BZERO, TIFF_BSCALE, TIFF_BUNIT" >> ${sub_dir_name}/info.txt
	# echo ${parameters} >> ${sub_dir_name}/info.txt
	
	# generate thumbnails and save
    tiff_file_name=$(printf "%04d_%02d_%02d" ${file_index} ${NTILE_X} ${NTILE_Y})
    thumb_file_name=${sub_dir_name}/overview_1024.tif
    convert -monitor -verbose -resize 1024x1024  ${TIFF_DIR}/$file ${thumb_file_name}
    convert -monitor -verbose -resize 512x512 ${thumb_file_name} ${UPLOAD_THUMB_DIR}/${tiff_file_name}_thumb.png
    
    let file_index=file_index+1
done

# save parameters to a text file
# parameters="${TIFF_NX} ${TIFF_NY} ${TIFF_NZ} ${NTILE_X} ${NTILE_Y} ${TIFF_DX} ${TIFF_DY} ${TIFF_DZ} ${TIFF_BZERO} ${TIFF_BSCALE} ${TIFF_BUNIT}"
echo "NX=${TIFF_NX}" >> ${UPLOAD_DIR}/info.txt
echo "NY=${TIFF_NY}" >> ${UPLOAD_DIR}/info.txt
echo "NZ=${TIFF_NZ}" >> ${UPLOAD_DIR}/info.txt
echo "TX=${NTILE_X}" >> ${UPLOAD_DIR}/info.txt
echo "TY=${NTILE_Y}" >> ${UPLOAD_DIR}/info.txt
echo "DX=${TIFF_DX}" >> ${UPLOAD_DIR}/info.txt
echo "DY=${TIFF_DY}" >> ${UPLOAD_DIR}/info.txt
echo "DZ=${TIFF_DZ}" >> ${UPLOAD_DIR}/info.txt

# zip the upload folder to .aar file
java -jar aar.jar -create ${UPLOAD_DIR}.aar ${UPLOAD_DIR}

# upload to DaRIS
# prepare metadata
optional_others=":others <"
if [ ! -z $TIFF_BZERO ]; then
    optional_others="${optional_others} :bzero ${TIFF_BZERO}"
fi
if [ ! -z $TIFF_BSCALE ]; then
    optional_others="${optional_others} :bscale ${TIFF_BSCALE}"
fi
if [ ! -z $TIFF_BUNIT ]; then
    optional_others="${optional_others} :bunit ${TIFF_BUNIT}"
fi
optional_others="${optional_others} >"

metadata="< :mbi.tiff.series < :number_of_images ${TIFF_NZ} :image_height ${TIFF_NX} :image_width ${TIFF_NY} \
:no_tiles_ver ${NTILE_X} :no_tiles_hoz ${NTILE_Y} \
:physical_unit < :dx ${TIFF_DX} :dy ${TIFF_DY} :dz ${TIFF_DZ} > \
${optional_others} > >"
#echo $metadata

zip_file_name=${UPLOAD_DIR}.aar

if [ ! -z $ORI_CID ]; then
    PROCESSED_STR=":input -vid ${dataset_name} $ORI_CID :processed true"
fi

dataset_cid=$( $MFCOMMAND om.pssd.dataset.derivation.create :pid ${STUDY_CID} :in file:${zip_file_name} :name "${dataset_name}" :meta "${metadata}" "${PROCESSED_STR}" | awk '{print $2}' | tr -d \" )
if [ -z ${dataset_cid} ]; then
    echo "fail to create asset"
	exit 1    
fi

echo "created dataset ${dataset_cid} successfully"

# zip the thumbnail directory
zip -r ${UPLOAD_THUMB_DIR}.zip $(ls -1 ${UPLOAD_THUMB_DIR}/*.png | sort -n)

echo ""
# send the thumbnail zip file to DaRIS
$MFCOMMAND om.pssd.object.thumbnail.set :id ${dataset_cid} :in file:${UPLOAD_THUMB_DIR}.zip

# clean up
if [ $REMOVE_ZIP_FILE -eq 1 ]; then
    rm ${zip_file_name}
fi
rm -r ${UPLOAD_DIR}
rm -r ${UPLOAD_THUMB_DIR}
rm ${UPLOAD_THUMB_DIR}.zip

# kill the background process dpingloop
if [ "$pollingID" != "" ]; then
 kill $pollingID
fi


echo ""
echo "uploaded successfully!"

#===== END OF SCRIPT =====

